package com.atguigu.gulimall.auth.controller;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.service.ILoginService;
import com.atguigu.gulimall.auth.service.IRegisterService;
import com.atguigu.gulimall.auth.service.ISendCodeService;
import com.atguigu.gulimall.auth.vo.UserLoginVO;
import com.atguigu.gulimall.auth.vo.UserRegistVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @author : wenchao.long
 * @date : Created in 2021/8/6 15:56 周五
 * @description :
 */
@Controller
@AllArgsConstructor
@Api(value = "登录接口", tags = "登录接口")
public class LoginController {

    private final ISendCodeService sendCodeService;

    private final IRegisterService registerService;

    private final ILoginService loginService;

    @GetMapping("/sms/sendCode")
    @ResponseBody
    @ApiOperation(value = "发送短信", notes = "发送短信")
    public R sendCode(@ApiParam("手机号") @RequestParam("phone") String phone) {
        return sendCodeService.sendCode(phone);
    }

    @PostMapping("/regist")
    public String regist(@Valid @RequestBody UserRegistVO userRegistVO, BindingResult result,
                         RedirectAttributes redirectAttributes) {
        return registerService.regist(userRegistVO, result, redirectAttributes);
    }

    @PostMapping("/login")
    public String login(UserLoginVO vo, RedirectAttributes redirectAttributes, HttpSession session) {
        return loginService.login(vo, redirectAttributes, session);
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null) {
            // 没登录
            return "login";
        }
        return "redirect:http://gulimall.com";
    }
}
